import axios from "axios";
import store from "store2";
import router from "@/router";
import { ElMessage } from "element-plus";
import { unref } from "vue";

// 创建一个axios实例
const myAxios = axios.create({
  timeout: 50000,
  baseURL: import.meta.env.VITE_APP_BASE_API,
});

// 添加请求拦截器
myAxios.interceptors.request.use(
  async function (config: any) {
    if (config.method.toUpperCase() === "GET" || config.method.toUpperCase() === "DELETE") {
      config.params = {
        ...config.data,
      };
    }
    config.headers.Authorization = store.get("Authorization");
    for (const key in config.data) {
      if (Object.hasOwnProperty.call(config.data, key)) {
        config.data[key] = unref(config.data[key]);
      }
    }
    return config;
  },
  function (error: any) {
    return Promise.reject(error);
  },
);

// 添加响应拦截器
myAxios.interceptors.response.use(
  function (res: any) {
    // 真正的接口返回数据在axios.data上
    const { data: response } = res;

    // 把状态码和需要的数据解构出来
    const { code, data, msg } = response;

    // 状态码为0才说明成功返回,否则抛出错误
    if (code != 200) {
      if (code == 403) {
        router.replace("/login");
        ElMessage.error("请重新登录");
        return Promise.reject(response);
      }
      if (code == 401) {
        ElMessage.error("没有访问权限");
        return Promise.reject(response);
      }
      ElMessage.error(msg);
      return Promise.reject(response);
    }

    // 成功则返回需要的数据
    return data;
  },
  function (error: any) {
    ElMessage.error("后端错误");
    // 对响应错误做点什么
    return Promise.reject(error);
  },
);

export default myAxios;
